<?php

namespace App\DataStore;

use App\Repository\RepositoryGeneral;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Redis\Redis;

class RedisGeneral extends RepositoryGeneral
{
    #[Inject]
    public Redis $redis;

    // 延时通用
    public function expire(string $key,int $ttl){
        if ($this->redis->exists($key)) {
            $this->redis->expire($key,$ttl);
        }
    }

    // 设置验证码
    public function setCaptchaRedis($key,array $data){
        $this->redis->set('captcha:'.$key,jsonEncode($data),60);
    }

    // 获取验证码
    public function getCaptchaRedis($key){
        $captcha =  (string)$this->redis->get('captcha:'.$key);
        // 校验过一次就删除这个key
        $this->redis->del('captcha:'.$key);
        return $captcha;
    }

    // 键值对获取全部的组织
    public function getOrgansRedis(){
        return (string)$this->redis->get('organs');
    }

    // 设置组织架构 map('organ_code':{organ_id,organ_name})
    public function setOrgansRedis(array $data){
         $this->redis->set('organs',jsonEncode($data));
    }

    // 用户Token 设置 详情
    public function setUserKey($key,array $data){
        $this->redis->set('user:organ'.getOrganIdByOrganCode().":".$key,jsonEncode($data),600);
    }

    // 通过用户token获取用户详情
    public function getUserKey($key){
        return (string)$this->redis->get('user:organ'.getOrganIdByOrganCode().":".$key);
    }

    // 根据机构设置组织架构
    public function setOrganDivision(int $organId,array $data){
        $this->redis->set('organs:'.$organId.':division',jsonEncode($data));
    }
    // 根据机构获取组织架构
    public function getOrganDivision(int $organId){
        return (string)$this->redis->get('organs:'.$organId.':division');
    }

    // 设置文件md5缓存
    public function setFileMd5(string $md5,array $data){
        $this->redis->set('files:'.$md5,jsonEncode($data));
    }

    // 获取md5文件
    public function getFileMd5(string $md5){
        return (string)$this->redis->get('files:'.$md5);
    }

    // 导入任务保存的数据
    public function setImport(string $key,array $data){
        $this->redis->set('import:organ:'.getOrganIdByOrganCode().":".$key,jsonEncode($data));
    }

    // 获取导入任务保存的数据
    public function getImport(string $key){
        return (string)$this->redis->get('import:organ:'.getOrganIdByOrganCode().":".$key);
    }
}